package com.xh.rufongwallpaper.controller;

import com.xh.rufongwallpaper.common.result.Result;
import com.xh.rufongwallpaper.common.utils.RequestUtils;
import com.xh.rufongwallpaper.entity.Device;
import com.xh.rufongwallpaper.service.DeviceService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * 设备控制器
 *
 * @author XH
 */
@RestController
@RequestMapping("/devices")
@RequiredArgsConstructor
@Tag(name = "设备API", description = "设备注册与认证相关接口")
public class DeviceController {

    private final DeviceService deviceService;

    /**
     * 注册设备
     *
     * @param device  设备信息
     * @param request HTTP请求
     * @return 设备信息
     */
    @PostMapping("/register")
    @Operation(summary = "注册设备", description = "注册设备并获取设备唯一标识")
    public Result<Device> registerDevice(
            @Parameter(description = "设备信息") @Valid @RequestBody Device device,
            HttpServletRequest request) {
        // 获取请求IP
        String ip = RequestUtils.getClientIp(request);
        device.setIp(ip);
        
        return Result.success(deviceService.registerDevice(device));
    }

    /**
     * 更新设备活跃时间
     *
     * @param deviceId 设备唯一标识
     * @return 结果
     */
    @PutMapping("/{deviceId}/active")
    @Operation(summary = "更新设备活跃时间", description = "更新设备的最后活跃时间")
    public Result<Boolean> updateDeviceActiveTime(
            @Parameter(description = "设备唯一标识") @PathVariable String deviceId) {
        boolean result = deviceService.updateDeviceActiveTime(deviceId);
        return Result.success(result);
    }

    /**
     * 获取设备信息
     *
     * @param deviceId 设备唯一标识
     * @return 设备信息
     */
    @GetMapping("/{deviceId}")
    @Operation(summary = "获取设备信息", description = "根据设备唯一标识获取设备信息")
    public Result<Device> getDeviceInfo(
            @Parameter(description = "设备唯一标识") @PathVariable String deviceId) {
        return deviceService.getDeviceByDeviceId(deviceId)
                .map(Result::success)
                .orElse(Result.failure("设备不存在"));
    }
} 